package com.ulook.lookplanet.main;

import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.ulook.lookplanet.R;
import com.ulook.lookplanet.common.ActivityCode;
import com.ulook.lookplanet.data.model.BaseUser;
import com.ulook.lookplanet.data.model.TUser;
import com.ulook.lookplanet.service.MsgService;
import com.ulook.lookplanet.service.SysMsgService;
import com.ulook.lookplanet.service.UserMsgService;
import com.ulook.lookplanet.ui.home.login.LoginActivity;
import com.ulook.lookplanet.ui.notifications.VMsgUser;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import androidx.navigation.ui.NavigationUI;

import org.litepal.LitePal;

/**
 * 主页面活动
 */
public class MainActivity extends AppCompatActivity {

    private MainViewModel viewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 检查权限
        checkPermission();

        viewModel = new ViewModelProvider(this, new MainViewModeFactory(getApplication())).get(MainViewModel.class);
        viewModel.getCurrUser().observe(this, baseUser -> {
            if(baseUser.getId() != 0){
                initMyService();
            }else {
                endMyService();
            }
        });

        LitePal.getDatabase(); // 创建数据库
        loginCheck();

        // 获取底部导航栏
        BottomNavigationView navView = findViewById(R.id.nav_view);
        // 获取 Host_Fragment
        NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
        // 导航控制器FragmentController
        NavController navController = navHostFragment.getNavController();
        // 与appBar模式的实现交互的NavigationUI方法的配置选项
        NavigationUI.setupWithNavController(navView, navController);

    }

    /**
     * 监听其他Activity的返回结果
     * @param requestCode
     * @param resultCode
     * @param intent
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        switch (resultCode){
            // 登陆页面返回结果
            case ActivityCode.LOGIN_RESULT_OK :
                loginMode((BaseUser) intent.getSerializableExtra("user"));
                break;
            // 设置页面获取权限的结果
            case ActivityCode.PERMISSION_CODE :
                if (resultCode == RESULT_OK) {
                    checkPermission();
                }
                break;
            default : break;
        }
    }

    @Override
    protected void onDestroy() {
        // 停止service
        endMyService();
        super.onDestroy();
    }

    /**
     * 开始Service
     */
    private void initMyService(){
        // 开启MsgService
        Log.d("#####","开启MsgService");
        Intent intentService = new Intent(this, SysMsgService.class);
        intentService.putExtra("currUserId", getCurrUser().getId());
        startService(intentService);
        Intent intentService2 = new Intent(this, UserMsgService.class);
        intentService2.putExtra("currUserId", getCurrUser().getId());
        startService(intentService2);
    }

    /**
     * 结束Service
     */
    private void endMyService(){
        Intent intentService = new Intent(this, SysMsgService.class);
        stopService(intentService);
        Intent intentService2 = new Intent(this, UserMsgService.class);
        stopService(intentService2);
    }

    /**
     * 登陆模式
     * @param user
     */
    public void loginMode(BaseUser user){
        // 设置当前用户
        viewModel.setCurrUser(user);
    }

    /**
     * 检查用户登录状态
     */
    private void loginCheck(){
        // 没有登陆信息，跳转到登陆页面
        if(!viewModel.loginCheck()){
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            startActivityForResult(intent, ActivityCode.LOGIN_REQUEST);
        }
    }

    /**
     * 获取当前用户
     */
    public BaseUser getCurrUser(){
        return viewModel.getCurrUser().getValue();
    }

    /**
     * 权限申请
     */
    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String[] permissions = new String[]{
                    Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.ACCESS_NETWORK_STATE,
                    Manifest.permission.INTERNET,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA,
                    Manifest.permission.WAKE_LOCK};
            for (String permission : permissions) {
                if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, permissions, ActivityCode.PERMISSION_CODE);
                    return;
                }
            }
        }
    }
    /**
     * 权限申请结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && requestCode == ActivityCode.PERMISSION_CODE) {
            for (int i = 0; i < permissions.length; i++) {
                // 没有权限，主动跳转到权限设置页面
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    Intent intent = new Intent();
                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", getPackageName(), null);
                    intent.setData(uri);
                    startActivityForResult(intent, ActivityCode.PERMISSION_CODE);
                    return;
                }
            }
        }
    }
}